package com.chookss.home.studyPlan;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.HomeActivityss;
import com.chookss.home.NavigationBaseActivity;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.video.VideoBaseActivity;
import com.google.gson.reflect.TypeToken;
import com.chookss.R;
import com.chookss.base.StaticClass;
import com.chookss.Urls;
import com.chookss.home.entity.StudyListEntity;
import com.chookss.home.entity.StudyPlanDayEntity;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.tools.MyEvent;
import com.chookss.tools.Utils;
import com.chookss.view.RecycleViewDivider;
import com.chookss.view.listener.StudyDialogListener;
import com.chookss.view.StudyPlanDialog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class StudyPlanDetailActivity extends BaseAct {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.rlTitle)
    RelativeLayout rlTitle;
    @BindView(R.id.tvReleaseName)
    TextView tvReleaseName;
    @BindView(R.id.tvReleaseTime)
    TextView tvReleaseTime;

    @BindView(R.id.rvView)
    RecyclerView rvView;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.tvCycle)
    TextView tvCycle;
    @BindView(R.id.tvDay)
    TextView tvDay;
    @BindView(R.id.tvComplete)
    TextView tvComplete;
    @BindView(R.id.tvReleaseDesc)
    TextView tvReleaseDesc;
    private String planCode, cycle = "1";
    private String startYear;
    private String planStatus;//1未开始2进行中3已结束
    private String effTime, invalidTime; //计划开始结束时间
    private String currentTime; //当前时间
    private List<String> months = new ArrayList<>();
    private List<StudyListEntity.TbKmerStudyPlanTaskItemsBean> list = new ArrayList<>();
    private List<List<StudyPlanDayEntity>> dayList = new ArrayList<>();
    private MyStudyAdapter myStudyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_my_study_detail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this,"1","04");
        planCode = getIntent().getStringExtra("planCode");
        cycle = getIntent().getStringExtra("cycle");
        effTime = getIntent().getStringExtra("effTime");
        invalidTime = getIntent().getStringExtra("invalidTime");
        planStatus = getIntent().getStringExtra("planStatus");
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rlTitle.getLayoutParams();
        layoutParams.setMargins(0, Utils.getStatusBarHeight(this), 0, 0);
        rlTitle.setLayoutParams(layoutParams);
        rvView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rvView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        myStudyAdapter = new MyStudyAdapter(R.layout.item_study_list, this, list);
        rvView.setAdapter(myStudyAdapter);

        SimpleDateFormat simpleDateFormat;
        Date date;
        //1未开始2进行中3已结束
        if ("3".equals(cycle)) {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            date = new Date(System.currentTimeMillis());

            tvDay.setText(Utils.getMonthCompareSize2(planStatus,simpleDateFormat.format(date), effTime, invalidTime));
        } else {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            date = new Date(System.currentTimeMillis());
            tvDay.setText(Utils.getTimeCompareSize2(planStatus,simpleDateFormat.format(date), effTime, invalidTime));
        }
        currentTime = simpleDateFormat.format(date);
        getData(true);
        // 可以自定义水印文字颜色、大小和旋转角度
        NavigationTools.setWaterMark(this,"8");
    }

    private void getData(boolean isFirst) {
        Map<String, String> map = new HashMap<>();
        map.put("planCode", planCode);
        map.put("periodName", tvDay.getText().toString());
        map.put("cycle", cycle);

        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<StudyListEntity>>() {
        }.getType(), null, Urls.getTaskDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<StudyListEntity>() {
            @Override
            public void onSuccess(StudyListEntity data) {
                if (tvTitle==null) {
                    return;
                }
                tvTitle.setText(data.getPlanTitle());
                tvComplete.setText("完成：" + data.getTotalCompleteNum() + "/" + data.getTotalTargetNum());
                tvReleaseName.setText("发布人：" + data.getEmployeeName());
                tvReleaseDesc.setText(data.getPlanDesc());
                tvReleaseTime.setText(Utils.getAccurateDate(data.getCreateTime()));
                effTime = data.getEffTime();
                invalidTime = data.getInvalidTime();
                tvTime.setText("时间：" + Utils.clearZeroTime(data.getEffTime()) + "——" + Utils.clearZeroTime(data.getInvalidTime()));

                startYear = Utils.getAccurateDate2(data.getEffTime(), 0, 4);
                //  (1:天  2: 周 3:月 4:年)
                cycle = data.getCycle();
                if ("2".equals(cycle)) {
                    tvCycle.setText("周期：每周一次");
                } else if ("3".equals(cycle)) {
                    tvCycle.setText("周期：每月一次");
                } else if ("4".equals(cycle)) {
                    tvCycle.setText("周期：每年一次");
                } else {
                    tvCycle.setText("周期：每天一次");
                }
                list.clear();
                list.addAll(data.getTbKmerStudyPlanTaskItems());
                if ("3".equals(cycle)) {
                    months = Utils.getYears(data.getEffTime(), data.getInvalidTime());
                } else {
                    months = Utils.getMonths(data.getEffTime(), data.getInvalidTime());
                }

                myStudyAdapter.notifyDataSetChanged();
                if (isFirst) {
                    getDayDetail();
                }

            }

            @Override
            public void onError(String errorMsg) {

                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }

    private int timeInt = 0;

    private void getDayDetail() {

        Map<String, String> map = new HashMap<>();
        map.put("planCode", planCode);
        map.put("employeeCode", new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        map.put("cycle", cycle);
        map.put("effTime", effTime);
        map.put("invalidTime", invalidTime);

        for (int i = 0; i < months.size(); i++) {
            List<StudyPlanDayEntity> list = new ArrayList<>();
            dayList.add(list);
        }
        for (int i = 0; i < months.size(); i++) {
            int y = i;
            map.put("timeStr", months.get(i));
            MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<StudyPlanDayEntity>>>() {
            }.getType(), null, Urls.selectCompletePlanForDay, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<StudyPlanDayEntity>>() {
                @Override
                public void onSuccess(List<StudyPlanDayEntity> data) {
                    timeInt++;
                    dayList.get(y).addAll(data);
                }

                @Override
                public void onError(String errorMsg) {
                }
            });
        }
    }

    class MyStudyAdapter extends BaseQuickAdapter<StudyListEntity.TbKmerStudyPlanTaskItemsBean, BaseViewHolder> {
        private Context context;

        public MyStudyAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<StudyListEntity.TbKmerStudyPlanTaskItemsBean> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolder helper, StudyListEntity.TbKmerStudyPlanTaskItemsBean item) {
            ImageView ivStudy = helper.getView(R.id.ivStudy);
            TextView tvStudyName = helper.getView(R.id.tvStudyName);
            TextView tvStudy = helper.getView(R.id.tvStudy);
            TextView tvStudySure = helper.getView(R.id.tvStudySure);
            tvStudyName.setText(item.getTaskName());
            tvStudy.setText("已完成" + item.getCompleteNum() + "/" + item.getTargetNum());
//            T001 观看视频 T002 发布视频 T003 评论视频 T004 完成练习题
//            T005 完成模拟卷 T006 学习课程 T007 发布课程
            if ("T001".equals(item.getTaskCode())) {
                Glide.with(context).load(R.drawable.icon_shipin).into(ivStudy);
            } else if ("T002".equals(item.getTaskCode())) {
                Glide.with(context).load(R.drawable.icon_fbsp).into(ivStudy);
            } else if ("T003".equals(item.getTaskCode())) {
                Glide.with(context).load(R.drawable.icon_pinglun).into(ivStudy);
            } else if ("T004".equals(item.getTaskCode())) {
                Glide.with(context).load(R.drawable.icon_practice).into(ivStudy);
            } else if ("T005".equals(item.getTaskCode())) {
                Glide.with(context).load(R.drawable.icon_wcmnj).into(ivStudy);
            } else {
                Glide.with(context).load(R.drawable.icon_practice).into(ivStudy);
            }
            int complete = Utils.changeNumber(item.getCompleteNum());
            int target = Utils.changeNumber(item.getTargetNum());
            int timeCompare=2;
            if ("3".equals(cycle)) {
                timeCompare = Utils.getMonthCompareSize(currentTime, tvDay.getText().toString());
            } else {
                timeCompare = Utils.getTimeCompareSize(currentTime, tvDay.getText().toString());
            }
            if (3 == timeCompare) {
                //还未开始
                tvStudySure.setVisibility(View.GONE);
            } else if (1 == timeCompare) {
                //已经结束
                if (complete >= target) {
                    tvStudySure.setText("已完成");
                    tvStudySure.setSelected(true);
                } else {
                    tvStudySure.setText("未完成");
                    tvStudySure.setSelected(true);
                }
                tvStudySure.setVisibility(View.VISIBLE);
            } else {
                if (complete >= target) {
                    tvStudySure.setText("已完成");
                    tvStudySure.setSelected(true);
                } else {
                    tvStudySure.setText("去完成");
                    tvStudySure.setSelected(false);
                }
                tvStudySure.setVisibility(View.VISIBLE);
            }
            tvStudySure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    if (tvStudySure.getText().toString().contains("去完成")) {

                        if ("T001".equals(item.getTaskCode())||"T003".equals(item.getTaskCode())) {
                            toPlan(0);
                        } else if ("T002".equals(item.getTaskCode())) {
                            Intent intent = new Intent(StudyPlanDetailActivity.this, HomeActivityss.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            EventBus.getDefault().post(new MyEvent("HomeRecord"));
                            finish();
                        } else {
                            toPlan(1);
                        }

//                    }
                }
            });
        }
    }
   private void toPlan(int type){
        //type 0小视频1题库
       if(type==0){
           if (PermissionSpUtils.getBoolean(this,"14",false)||PermissionSpUtils.getBoolean(this,"19",false)) {
               String code1 = new ShareUtils().getString(StudyPlanDetailActivity.this, StaticClass.BOTTOM_1_CODE, "");
               String code3 = new ShareUtils().getString(StudyPlanDetailActivity.this, StaticClass.BOTTOM_3_CODE, "");
               if ("14".equals(code1) || "14".equals(code3) || "19".equals(code1) || "19".equals(code3)) {
                   Intent intent = new Intent(StudyPlanDetailActivity.this, HomeActivityss.class);
                   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                   startActivity(intent);
                   EventBus.getDefault().post(new MyEvent("HomeVedioBottom1"));
                   //定时器 倒计时
                   Observable.timer(400, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                           .subscribe(new Consumer<Long>() {
                               @Override
                               public void accept(Long aLong) {
                                   try {
                                       EventBus.getDefault().post(new MyEvent("HomeVedio1"));
                                   } catch (Exception e) {
                                       e.printStackTrace();
                                   }
                               }
                           });
                   finish();
               } else {
                   Intent  intent = new Intent(StudyPlanDetailActivity.this, VideoBaseActivity.class);
                   intent.putExtra("index",1);
                   startActivity(intent);
               }

           } else {
               MyToast.show("管理员已关闭视频功能");
           }
       }else{
           //题目被练习
           if (PermissionSpUtils.getBoolean(this,"13",false)) {
               String code1 = new ShareUtils().getString(StudyPlanDetailActivity.this, StaticClass.BOTTOM_1_CODE, "");
               String code3 = new ShareUtils().getString(StudyPlanDetailActivity.this, StaticClass.BOTTOM_3_CODE, "");
               if ("13".equals(code1) || "13".equals(code3)) {
                   Intent   intent = new Intent(StudyPlanDetailActivity.this, HomeActivityss.class);
                   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                   startActivity(intent);
                   EventBus.getDefault().post(new MyEvent("HomeBottom_Tiku"));
                   finish();
               } else {
                   Intent  intent = new Intent(StudyPlanDetailActivity.this, NavigationBaseActivity.class);
                   intent.putExtra("type",0);
                   startActivity(intent);
               }
           } else {
               MyToast.show("管理员已关闭题库功能");
           }
       }
   }
    private StudyPlanDialog dialog = null;
    private StudyPlanDialog yearDialog = null;

    @OnClick({R.id.ivBack, R.id.tvDay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvDay:
                if (tvDay==null) {
                    return;
                }
                if (timeInt==0) {
                    MyToast.show("网络异常，请稍后重试");
                    return;
                }
                if (timeInt == months.size()) {
                    if ("3".equals(cycle)) {
                        if (yearDialog == null) {
                            yearDialog = new StudyPlanDialog(StudyPlanDetailActivity.this, dayList, months, cycle, new StudyDialogListener() {
                                @Override
                                public void onStudyClick(String date) {
                                    tvDay.setText(date);
                                    getData(false);
                                }
                            });
                        }
                        yearDialog.show();
                    } else {
                        if (dialog == null) {
                            dialog = new StudyPlanDialog(StudyPlanDetailActivity.this, dayList, months, cycle, new StudyDialogListener() {
                                @Override
                                public void onStudyClick(String date) {
                                    tvDay.setText(date);
                                    getData(false);
                                }
                            });
                        }
                        dialog.show();
                    }
                }
                break;
            default:
        }
    }
}
